<?php

namespace common\models;

use yii\data\Pagination;
use yii\data\ArrayDataProvider;
use Yii;
use common\models\TaskDesc;

/**
 * This is the model class for table "xd_task". 
 * 
 * @property string $id
 * @property string $task_id
 * @property string $task_title
 * @property string $sub_title
 * @property integer $task_type
 * @property integer $connect_type
 * @property string $link
 * @property integer $status
 * @property integer $is_fixed
 * @property integer $single_reward
 * @property string $real_price
 * @property integer $force_play_time
 * @property integer $single_limit_count
 * @property integer $finish_count
 * @property integer $total_limit_count
 * @property integer $finish_status
 * @property integer $is_need_verify
 * @property integer $put_in_status
 * @property string $remark
 * @property string $start_time
 * @property string $end_time
 * @property string $create_time
 * @property string $update_time
 */
class Task extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc 
     */
    public static function tableName() {
        return 'xd_task';
    }

    /**
     * @inheritdoc 
     */
    public function rules() {
        return [
//            [['task_type', 'connect_type', 'status', 'is_fixed', 'single_reward', 'force_play_time', 'single_limit_count', 'finish_count', 'total_limit_count', 'finish_status', 'is_need_verify', 'put_in_status'], 'integer'],
//            [['real_price'], 'number'],
//            [['start_time', 'end_time', 'create_time', 'update_time'], 'safe'],
//            [['task_id'], 'string', 'max' => 38],
//            [['task_title', 'sub_title', 'link'], 'string', 'max' => 200],
//            [['remark'], 'string', 'max' => 500],
//            [['task_id'], 'unique'],
            [['single_reward','force_play_time'],'integer'],
            [['real_price'], 'number'],
            [['single_reward','force_play_time','total_limit_count','single_limit_count'],'compare', 'compareValue' => 0, 'operator' => '>='],
        ];
    }

    /**
     * @inheritdoc 
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('app', '主键id'),
            'task_id' => Yii::t('app', '任务id（唯一）'),
            'task_title' => Yii::t('app', '标题'),
            'sub_title' => Yii::t('app', '副标题'),
            'task_type' => Yii::t('app', '任务类型'),
            'connect_type' => Yii::t('app', '接入方式[默认1外链（直接外链跳转），2文件上传，3需说明页跳转]'),
            'link' => Yii::t('app', '任务外链'),
            'status' => Yii::t('app', '任务状态'),
            'is_fixed' => Yii::t('app', '是否固定任务 0不是，1是，默认0'),
            'single_reward' => Yii::t('app', '单次奖励'),
            'real_price' => Yii::t('app', '实际单价'),
            'force_play_time' => Yii::t('app', '强制播放时长'),
            'single_limit_count' => Yii::t('app', '单用户限制次数'),
            'finish_count' => Yii::t('app', '任务完成数'),
            'total_limit_count' => Yii::t('app', '任务限制总次数'),
            'finish_status' => Yii::t('app', '当前完成任务状态[0未完成，1已完成,2不限]'),
            'is_need_verify' => Yii::t('app', '是否需要审核[0不需要，1需要]'),
            'put_in_status' => Yii::t('app', '投放状态[0关闭，1开启]'),
            'remark' => Yii::t('app', '任务备注'),
            'start_time' => Yii::t('app', '开始时间'),
            'end_time' => Yii::t('app', '结束时间'),
            'create_time' => Yii::t('app', '创建时间'),
            'update_time' => Yii::t('app', '修改时间'),
        ];
    }

    /**
     * 任务列表
     * @return array
     */
    public static function getTaskList($params = array()) {
        $model = self::find();

        //标题 like
        if (isset($params['title']) && $params['title'] != '') {
            $model->andWhere('task_title like :title');
            $model->addParams([':title' => '%' . $params['title'] . '%']);
        }
        
        if (isset($params['type']) && $params['type']) {
            $model->andWhere('task_type = :type');
            $model->addParams([':type' => $params['type']]);
        }
        
        $model->andWhere(['status' => 1]);

        //总数
        $count = $model->count();
        $model->orderBy('is_fixed desc,create_time desc');
        $offset = ( $params['page'] - 1 ) * 10;
        $limit = 10;
        $model->offset($offset)->limit($limit);
        $list = $model->asArray()->all();

        $taskTypeList = TaskType::getAllTaskType();
        $typeList = array_column($taskTypeList, null, 'id');
        foreach ($list as $k => $v) {
            if (isset($typeList[$v['task_type']])) {
                $list[$k]['task_type'] = $typeList[$v['task_type']]['name'];
            } else {
                $list[$k]['task_type'] = '暂无';
            }
        }
        //类型列表
        $data['taskTypeList'] = $taskTypeList;
        // 列表
        $data['dataProvider'] = new ArrayDataProvider([
            'allModels' => $list,
        ]);
        $data['pagination'] = new Pagination(array(
            'defaultPageSize' => 10,
            'totalCount' => $count,
        ));
        return $data;
    }
    
    /**
  `connect_type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '接入方式[默认1外链（直接外链跳转），2文件上传，3需说明页跳转]',
  `link` varchar(200) NOT NULL DEFAULT '' COMMENT '任务外链',
  `status` tinyint(3) NOT NULL DEFAULT '1' COMMENT '任务状态',
  `is_fixed` tinyint(3) NOT NULL DEFAULT '1' COMMENT '是否固定任务 0不是，1是，默认0',
  `force_play_time` int(11) NOT NULL DEFAULT '0' COMMENT '强制播放时长',
     */
    
    public function createTask(){
        $postData = Yii::$app->request->post();
        $id = $postData['id'];
        if($id){
            $model = self::findOne($id);
        }else{
            $model = new self;
        }
        $type = trim($postData['type']);
        $model->task_title = $postData['title'];
        $model->sub_title = $postData['sub_title'];
        $model->single_reward = $postData['single_reward'];
        $model->real_price = $postData['real_price'];
        $model->single_limit_count = $postData['single_limit_count'];
        $model->total_limit_count = $postData['total_limit_count'];
//        $model->finish_count = $postData['finish_count'];
        $model->is_need_verify = $postData['is_need_verify'];
//        $model->finish_status = $postData['finish_status'];
        $now = date('Y-m-d H:i:s');
        if($postData['put_in_status'] == '1'){
            $model->start_time = $now;
        }elseif($postData['put_in_status'] == '0' && isset($postData['id']) && $model->put_in_status == 1){
            $model->end_time = $now;
        }
        $model->put_in_status = $postData['put_in_status'];
        $model->remark = $postData['remark'];
        $model->create_time = $now;
        if(in_array($type,['下载','分享','分享享点app任务','试用'])){
            if($postData['connect_type'] != '2' && trim($postData['link']) == ''){
                echo json_encode(['status' => 1 , 'msg' => '请填写外链！']);
                exit;
            }
        }
        if($postData['connect_type'] == '2'){
            if(trim($postData['link']) == ''){
                echo json_encode(['status' => 1 , 'msg' => '请上传文件！']);
                exit;
            }
        }
        switch ($type){
            case '有偿阅读任务':
                if(!$id){
                    $model->task_id = 'YCYD'.create_task_uuid();
                }
                $model->task_type = 1;
                $model->is_fixed = 1;
                break;
            case '签到任务':
                if(!$id){
                    $model->task_id = 'QD'.create_task_uuid();
                }
                $model->task_type = 2;
                $model->is_fixed = 1;
                $model->single_reward = 0;
                $model->real_price = 0;
                break;
            case '分享享点app任务':
                if(!$id){
                    $model->task_id = 'XDSH'.create_task_uuid();
                }
                $model->task_type = 3;
                $model->is_fixed = 1;
                $model->link = trim($postData['link']);
                break;
            case '分享':
                if(!$id){
                    $model->task_id = 'SH'.create_task_uuid();
                }
                $model->task_type = 4;
                $model->link = trim($postData['link']);
                break;
            case '视频':
                if(!$id){
                    $model->task_id = 'VD'.create_task_uuid();
                }
                $model->connect_type = $postData['connect_type'];
                $model->link = $postData['link'];
                $model->force_play_time = $postData['force_play_time'];
                $model->task_type = 5;
                break;
             case '活动':
                if(!$id){
                    $model->task_id = 'AC'.create_task_uuid();
                }
                $model->link = $postData['link'];
                $model->task_type = 6;
                break;
            case '下载':
                if(!$id){
                    $model->task_id = 'DL'.create_task_uuid();
                }
                $model->connect_type = $postData['connect_type'];
                $model->link = $postData['link'];
                $model->task_type = 7;
                break;
            case '试用':
                if(!$id){
                    $model->task_id = 'TS'.create_task_uuid();
                }
                $model->connect_type = $postData['connect_type'];
                $model->link = $postData['link'];
                $model->task_type = 8;
                break; 
            case '图文':
                if(!$id){
                    $model->task_id = 'IT'.create_task_uuid();
                }
                $model->connect_type = $postData['connect_type'];
                $model->link = $postData['link'];
                $model->task_type = 9;
                break;
            default :
                return false;
        }
        if(!$model->validate()){
            $errors = $model->getErrors();
            if(isset($errors['single_reward'])){
                echo json_encode(['status' => 1,'msg'=>'单次奖励须为正整数！']);
                exit;
            }
            if(isset($errors['real_price'])){
                echo json_encode(['status' => 1,'msg'=>'实际单价须为数字！']);
                exit;
            }
            if(isset($errors['force_play_time'])){
                echo json_encode(['status' => 1,'msg'=>'强制播放时长须为正整数！']);
                exit;
            }
            if(isset($errors['single_limit_count'])){
                echo json_encode(['status' => 1,'msg'=>'单用户限制次数须为正整数！']);
                exit;
            }
            if(isset($errors['total_limit_count'])){
                echo json_encode(['status' => 1,'msg'=>'任务限制总次数须为正整数！']);
                exit;
            }
        }
        $res = $model->save();
        $data = [];
        if($res && !empty($postData['task_desc'])){
            foreach($postData['task_desc'] as $v){
                if(trim($v['task_desc']) == ''){
                    continue;
                }
                $data[] = [
                    'task_id' => $model->task_id,
                    'task_desc' => $v['task_desc'],
                    'img_url' => $v['img_url'],
                    'create_time' => date('Y-m-d H:i:s')
                ];
            }
            $taskDesc = new TaskDesc();
//            $taskDesc->task_id = $model->task_id;
            $taskDesc->deleteAll('task_id="'.$model->task_id.'"');
            $res = Yii::$app->db->createCommand()->batchInsert('xd_task_desc',['task_id','task_desc','img_url','create_time'],$data)->execute();
        }
        return $res;
    }
    
    /**
     * 根据id获取任务信息
     * @param type $id
     * @return type
     */
    public static function getById( $id )
    {
        if( !$id ){
            return [];
        }
        $model = self::find();
        $model->andWhere( [ 'id' => $id ] );
        $model->andWhere( [ 'status' => 1 ] );
        $task = $model->asArray()->one();
        if( $task ){
            $desc_model = TaskDesc::find();
            $desc_model->andWhere( [ 'task_id' => $task['task_id'] ] );
            $task_desc = $desc_model->asArray()->all();
            $task['desc'] = $task_desc;
            $short = explode('/',$task['link']);
            $task['short_name'] = $short[count($short)-1];
        }
        return $task;
    }

}
